import qiniu from "qiniu";
import path from 'path';
import im from 'imagemagick';

import * as mq from '../mq/index';
import logger from './logger';
import request from 'request';
import fs from 'fs';

qiniu.conf.ACCESS_KEY = 'wGuu4_aBllf1M2d4DYnkylbXMauLUQxqnBF8pI06' || 'kfRXRAVDac1ay9YPDDzpMgluABj53HxHmhkSXbB_';
qiniu.conf.SECRET_KEY = 'E0GP5w1hItFKRCoDJfoi0r-cw2xKwxfM-E2jz3BE' || 'NL-pvdrS-Vz5zYfv2WBWneA6ymYNYIJGum5CyynD';

function uptoken(bucket, key, options) {
    var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
    for(let p in options) {
        putPolicy[p] = options[p];
    }
    return putPolicy.token();
}

function uploadFile(uptoken, key, localFile, callback) {
    var extra = new qiniu.io.PutExtra();
    qiniu.io.putFile(uptoken, key, localFile, extra, callback);
}

async function upload(args, options) {
    try {
        let filePath = args.filePath;
        let bucket = args.bucket || 'zhixiaocloud';

        let key = path.basename(filePath);
        options = Object.assign({
            persistentNotifyUrl: 'http://test.zhixiaocloud.com/api/v1/qiniu/notify'
        }, options)

        let token = uptoken(bucket, key, options);
        return new Promise((resovle, reject) => {
            uploadFile(token, key, filePath, function(err, ret) {
                console.log(err, ret)
                if(!err) {
                    resovle(ret);
                } else {
                    reject(err);
                }
            });
        });
    } catch (e) {
        logger.error(e, 'qiniu.upload');
    }
}

 async function download(args) {
    try {
        let url = 'http://onkk6zl0a.bkt.clouddn.com';
        let policy = new qiniu.rs.GetPolicy();
        let downloadUrl = policy.makeRequest(url);
        let stream = fs.createWriteStream(args.dest);

        await new Promise((resovle, reject) => {
            request(`${url}/${args.key}`).pipe(stream).on('close', function (err, result) {
                console.log(err, result);
                if(!err) {
                    resovle();
                } else {
                    reject(err);
                }
            });
        })
    } catch (e) {
        logger.trace(e, 'qiniu.download');
    }
}

async function composeImg(sour, dest) {
    return new Promise((resolve, reject) => {
        let args = sour.concat(['-append', dest])
        im.convert(args, function (err) {
            if(!err) {
                resolve();
            } else {
                reject(err);
            }
        })
    });
}

/**
 *
 * @returns {Promise.<void>}
 * 文件上传到七牛
 */
export async function file2qiniu(args) {
    try {
        let { filePath, examId } = args;
        //默认是资源转化
        let options = Object.assign({
            persistentOps: 'yifangyun_preview/v2/format=jpg' || 'yifangyun_preview',//默认是pdf
            persistentPipeline: 'word2jpg' || 'word2pdf' || 'word2jpg',
            callbackBody: `examId=${examId}`,
            persistentNotifyUrl: `http://test.zhixiaocloud.com/api/v1/qiniu/notify?examId=${examId}`
        }, options);

        let result = await qiniuService.upload({ filePath, examId }, options);
    } catch (e) {
        logger.error(e, 'file2qiniu');
    }
}

/**
 *
 * @param args
 * @returns {Promise.<void>}
 * 七牛回调
 */
export async function qiniuCb(args) {
    try {
        console.log('七牛cb', args);
        let pipeline = args.pipeline.split('.')[1];
        let examId = args.user.examId;
        let inputKey = args.inputKey;
        let inputKeyName = inputKey.split('.')[0];

        if(pipeline.indexOf('word2') > -1) {
            let exam = await Exam.findById(examId);
            let examCat = new config.ExamCat(exam._id, exam.subject);
            //如果上传试卷时，还没有选学科，那么此时转化后的资源和原资源不在同一个文件夹里
            let dest = exam.subject ? examCat.examTmpl : examCat.examGroupTmp;

            let jpgDest = path.join(dest, `${inputKeyName}.jpg`);
            if(pipeline == 'word2pdf') {
                let key = args.items[0].key;
                let pdfDest = path.join(dest, `${inputKeyName}.pdf`);

                await qiniuService.download({ key: key, dest: pdfDest});
                await im.pdfToImage({sour: pdfDest, dest: jpgDest});

            }

            if(pipeline == 'word2jpg') {
                let keys = args.items[0].keys.sort();
                let dests = [];
                for(let [i, key] of keys.entries()) {
                    let dir = path.join(dest, key);
                    dests.push(dir);
                    await download({ key: key, dest: dir });
                }
                await composeImg(dests, jpgDest);
            }

            let imgData = await identifyImg(jpgDest);
            let attachment = await Attachment.create({
                name: path.basename(jpgDest),
                type: 'image/jpeg',
                path: jpgDest,
                height: imgData.height,
                width: imgData.width
            });
            await exam.update({
                attachment: attachment._id
            });
        }

    } catch (e) {
        logger.error(e, 'file2qiniu');
    }
}